/**
 * Created by tanbingqin on 2020/7/29.
 */
import { messages, deepFullCopy } from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import constants from 'share/constants'
import { Button, Form, Switch, Input, Checkbox, Radio, InputNumber, Row, Col, message, Spin, Alert, Tooltip, Icon, Select, Affix, Popover } from 'antd'
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const CheckboxGroup = Checkbox.Group;
const Option = Select.Option;
import formService from 'containers/setting/form/form.service'
import Chooser from 'components/chooser'
import errorMessage from 'share/errorMessage'
import formUtil from 'containers/setting/form/form-util'
import menuRoute from 'routes/menuRoute'
import AllocationExpense from "../../comp/expense";
import CompactInput from "components/compact-input";
import chooserData from "share/chooserData";

class ExpenseReportProperty extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      disabled: false, //所有表单适用这个属性
      form: {},  //表单信息
      setOfBooksId: '', //表单上的帐套
      priorityValue: {}, //所属组织，启用公司控件value
      priorityRangeValue: {}, //所属组织控件的rangeValue，包含整个对象信息
      paymentTypeList: [], //付款方式下拉列表选择项
      contractEnable: false, //是否关联合同
      contractRequired: false, //关联合同时，是否合同必填
      isBudgetEr: false, //报销单提交时是否占用预算
      isMultiLine: true, //默认开启多付款行
      isNotPayeeBring: true, //差旅，日常，费用报销单是否收款方默认不带出
      addVenMaster: 'false', //差旅，日常，费用报销单和单行，多行借款单，是否允许新增供应商
      availableType: [],
      rangeExpense: {
        range: 'ALL',
        value: []
      },
      writeOffEnabled: true,
      writeOffWithDepartment: false,
      expenseTypeScope: {
        range: 'ALL',
        value: []
      },
      prepaymentType: {
        range: 'ALL',
        value: []
      },
      paymentMethod: '',
      applicationEnabled: false,
      requestFormType: {
        range: 'ALL',
        value: []
      },
      relatedApplicationScope: '',
      relatedApplicationRequired: false,
      prepaymentTypeRangeDisabled: true,
      requestFormTypeRangeDisabled: true
    };
    this.formList = menuRoute.getRouteItem('form-list','key'); //表单列表页
  }

  componentDidMount() {
    this.initPaymentTypeList();
    this.initFormData();
    //处理表单属性
    this.initCustomFormPropertyMap();
  };

  initPaymentTypeList = () => {
    formService.getPaymentMethod().then(res => {
      this.setState({paymentTypeList: res.data || [], loading: false});
    });
  };

  initFormData = () => {
    const { form } = this.context;
    this.setState({
      form,
      disabled: !form.edit,
      setOfBooksId: form.setOfBooksId
    });
    //处理所属组织，启用公司
    this.initPriorityValue();
  };

  initCustomFormPropertyMap = () => {
    const { form } = this.context;
    let propertyMap = form.customFormPropertyMap;
    let rangeExpense = {
      range: (form.expenseTypesDTO && form.expenseTypesDTO.visibleScope === 1001) ? 'ALL' : 'PARTIAL',
      value: form.expenseTypesDTO.expenseTypes.map(i => ({ expenseTypeOID: i.expenseTypeOID, name: i.name }))
    };
    let stateValue = { rangeExpense };
    for (let key in propertyMap) {
      let value = (key === 'related.application.property' || key === 'prepayment.writeoff' ||
        key === 'corp.payment.available.type' || key === 'prepayment.type') ?
        JSON.parse(propertyMap[key] || null) :
        propertyMap[key];
      if (formUtil.getStateKey(key, value)) {
        Object.assign(stateValue, formUtil.getStateKey(key, value));
      }
    }
    this.setState(stateValue);
  };

  initPriorityValue = () => {
    const { form } = this.context;
    let priorityValue = {
      levelCode: form.fromType === 2 ? "SET_OF_BOOK" : "COMPANY",
      levelOrgId: form.fromType === 2 ? form.setOfBooksId : form.companyOID,
      levelOrgName: form.fromType === 2 ? form.setOfBooksName : form.companyName
    };
    if (form.fromType === 2 && form.customFormCompanyRequest.visibleCompanyScope === '2') {
      priorityValue.distribution = {companies: form.customFormCompanyRequest.companyList};
    }
    let priorityRangeValue = {};
    if (form.fromType === 2) {
      priorityRangeValue = {
        setOfBooksId: form.setOfBooksId,
        setOfBooksName: form.setOfBooksName
      }
    }
    if (form.fromType === 1) {
      priorityRangeValue = {
        id: form.companyId,
        companyOID: form.companyOID,
        name: form.companyName,
        setOfBooksId: form.setOfBooksId
      }
    }
    this.setState({priorityValue, priorityRangeValue});
  };

  handleStatusChange = (value, key) => {
    const { formOID } = this.context;
    const { availableType } = this.state;
    if (key === 'isBudgetCa' || key === 'isBudgetEr') {
      if (formOID) {
        let serviceName = key === 'isBudgetEr' ? 'getFormIsHasData' : 'getCaFormIsHasData';
        formService[serviceName](formOID).then(res => {
          if (res.data) {
            //有数据时不可更改配置
            message.error(messages('request-2.key21')/*已有相应的业务数据，不可修改。*/);
          } else {
            //没有数据时可更改配置
            this.setState({
              [key]: value
            });
          }
        });
      } else {
        this.setState({
          [key]: value
        });
      }
    } else if(key === 'availableType') {
      availableType.indexOf(value) > -1 ? availableType.delete(value) : availableType.push(value);
      this.setState({ availableType });
    } else if(key === 'prepaymentType' || key === 'requestFormType') {
      let parsedValue = value.map(i => key === 'prepaymentType' ? ({
        id: i.id,
        prepaymentTypeName: i.prepaymentTypeName
      }) : ({
        formOID: i.formOID,
        formName: i.formName
      }));
      this.setState({
        [key]: {
          range: 'PARTIAL',
          value: parsedValue
        }
      })
    } else {
      this.setState({
        [key]: value
      });
    }
  };

  handleChangeRange = (value, key) => {
    if(value === 'ALL') {
      this.setState({ [key]: { range: 'ALL', value: [] }, [key + 'RangeDisabled']: true });
    } else {
      this.setState({ [key]: { range: 'PARTIAL', value: [] }, [key + 'RangeDisabled']: false });
    }
  };

  //value为true 说明要刷新列表，为event点击事件时不做刷新
  goBack = (value) => {
    const { close } = this.context;
    if (close) {
      close(value);
    } else {
      this.context.router.push(this.formList.url);
    }
  };

  handleSave = () => {
    const { formOID } = this.context;
    const { refreshBase } = this.props;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err && this.validateData(values)) {
        let params = this.processValue(values);
        this.setState({loading: true});
        formService.saveNewForm(params).then(res => {
          this.setState({loading: false});
          message.success(messages('common.save.success',{arg1: res.data.formName})/*{arg1} 保存成功*/);
          refreshBase(formOID, 'property');
        }).catch((err) => {
          this.setState({loading: false});
          errorMessage(err.response);
        });
      }
    });
  };

  validateData = () => {
    const { availableType, paymentMethod, relatedApplicationScope, applicationEnabled } = this.state;
    if(!availableType.length) {
      message.error(messages('request-2.key395')/*请选择启用功能类型*/);
      return false;
    }

    if(!paymentMethod) {
      message.error(messages('request-2.key396')/*请选择默认付款方式*/);
      return false;
    }

    if(applicationEnabled && !relatedApplicationScope) {
      message.error(messages('request-2.key397')/*请选择关联申请单范围*/);
      return false;
    }
    return true;
  };

  processValue = (values) => {
    const { formOID } = this.context;
    const { form, rangeExpense } = this.state;
    let params = {
      ...form,
      customFormFields: form.customFormFields
    };

    //处理表单属性
    params.customFormPropertyMap = this.processPropertyMap(values);
    params['expenseTypesDTO'] = {
      entityOID: formOID,
      visibleScope: rangeExpense.range === 'PARTIAL' ? 1002 : 1001,
      expenseTypeOIDs: rangeExpense.value.map(expense => expense.expenseTypeOID).filter(i => !!i)
    };
    return params;
  };

  //处理对公表单属性，相关文档：https://note.youdao.com/ynoteshare1/index.html?id=479640577ff39cb7a5c98d5d37abdc10&type=note
  processPropertyMap = () => {
    const { formType } = this.context;
    const { contractEnable, addVenMaster, isBudgetEr, contractRequired,
      availableType, rangeExpense, writeOffEnabled, writeOffWithDepartment, expenseTypeScope, prepaymentType,
      paymentMethod, applicationEnabled, requestFormType, relatedApplicationScope, relatedApplicationRequired
    } = this.state;
    let propertyMap = {};
    //对公支付单表单属性
    if (formType === 3004) {
      propertyMap['corp.payment.available.type'] = JSON.stringify(availableType);
      propertyMap['prepayment.writeoff'] = JSON.stringify({
        enable: writeOffEnabled,
        writeOffWithDepartment: writeOffWithDepartment,
        expenseTypeScope: expenseTypeScope.value.filter(i => !!i)
      });
      propertyMap['budget.er.enabled'] = isBudgetEr;
      propertyMap['prepayment.type'] = JSON.stringify({prepaymentTypeList: prepaymentType.value});
      propertyMap['payment.method'] = paymentMethod;
      propertyMap['related.application.property'] = JSON.stringify({
        enable: applicationEnabled,
        formDataList: requestFormType.value,
        relatedApplicationScope: relatedApplicationScope,
        required: relatedApplicationRequired
      });
      propertyMap['report.property.associated.contract.enabled'] = contractEnable;
      propertyMap['associate.contract.required'] = contractEnable ? contractRequired : false;
      propertyMap['document.venmasteradd.enable'] = addVenMaster;
      propertyMap['import.unify.data'] = 'false';
      propertyMap['report.property.pay.multi.lines'] = 'true';
      propertyMap['document.payee.not.bring'] = 'true';
      propertyMap['report.subsidy.config'] = JSON.stringify({withSubsidies: false});
    }
    return propertyMap;
  };

  render() {
    const { loading, disabled, setOfBooksId, availableType, contractEnable, contractRequired, writeOffEnabled,
      isBudgetEr, writeOffWithDepartment, expenseTypeScope, prepaymentType, applicationEnabled, requestFormType,
      relatedApplicationScope, relatedApplicationRequired, addVenMaster, paymentTypeList, paymentMethod,
      prepaymentTypeRangeDisabled, requestFormTypeRangeDisabled, rangeExpense, priorityValue
    } = this.state;
    const formItemLayout = {
      labelCol: {span: 4},
      wrapperCol: {span: 8, offset: 1},
    };
    return (
      <div className="form-new-edit new-form form-detail-base corporate-payment-form-detail">
        <Spin spinning={loading}>
          <Form>
            <FormItem {...formItemLayout} label={messages('request-2.key398')/*启用功能类型*/} required>
              <Checkbox
                key='1001'
                value={1001}
                checked={availableType.indexOf(1001) > -1}
                onChange={e => this.handleStatusChange(e.target.value, 'availableType')}
              >
                {messages('request-2.key399')/*到票支付*/}
              </Checkbox>
              <div className='font-description'>{messages('request-2.key400')/*启用后，对公支付单界面显示新建到票支付按钮，用于录入收到发票后申请付款的单据*/}</div>
              {
                availableType.indexOf(1001) > -1 && (
                  <div>
                    <FormItem
                      required
                      {...formItemLayout}
                      label={messages('request-2.key136')/*可见费用类型*/}
                    >
                      <div className="normal-width">
                        <AllocationExpense
                          value={rangeExpense}
                          setOfBooksId={setOfBooksId}
                          disabled={disabled || !setOfBooksId}
                          parser={value => ({range: value.range, value: value.value || []})}
                          hidden={['RELATED']}
                          onChange={value => this.handleStatusChange(value, 'rangeExpense')}
                        />
                      </div>
                    </FormItem>
                    <FormItem
                      required
                      {...formItemLayout}
                      label={messages('request-2.key401')/*预付核销*/}
                      extra={messages('request-2.key402')/*控制录入到票支付数据时，是否开启预付款核销入口*/}
                    >
                      <RadioGroup
                        disabled={disabled}
                        value={writeOffEnabled}
                        onChange={e => this.handleStatusChange(e.target.value, 'writeOffEnabled')}
                      >
                        <Radio value={true}>{messages('request-2.key329')/*开启*/}</Radio>
                        <Radio style={{marginLeft: 50}} value={false}>{messages('request-2.key330')/*不开启*/}</Radio>
                      </RadioGroup>
                    </FormItem>

                    {
                      writeOffEnabled && (
                        <div>
                          <FormItem
                            required
                            {...formItemLayout}
                            label={<span><Icon type="enter" className="rotate-icon" />{messages('request-2.key403')/*按部门核销*/}</span>}
                            extra={messages('request-2.key404')/*控制核销时，是否需要按部门筛选有余额的预付款进行核销*/}
                          >
                            <RadioGroup
                              disabled={disabled}
                              value={writeOffWithDepartment}
                              onChange={e => this.handleStatusChange(e.target.value, 'writeOffWithDepartment')}
                            >
                              <Radio value={true}>{messages('request-2.key329')/*开启*/}</Radio>
                              <Radio style={{marginLeft: 50}} value={false}>{messages('request-2.key330')/*不开启*/}</Radio>
                            </RadioGroup>
                          </FormItem>
                          {writeOffWithDepartment && (
                            <FormItem
                              required
                              {...formItemLayout}
                              label={<span><Icon type="enter" className="rotate-icon" />{messages('request-2.key405')/*应用费用类型范围*/}</span>}
                            >
                              <div className="normal-width">
                                <AllocationExpense
                                  value={expenseTypeScope}
                                  setOfBooksId={setOfBooksId}
                                  disabled={disabled || !setOfBooksId}
                                  parser={value => ({range: value.range, value: value.value.map(i => ({
                                      expenseTypeOID: i.expenseTypeOID,
                                      name: i.name
                                    })) || []})
                                  }
                                  onChange={value => this.handleStatusChange(value, 'expenseTypeScope')}
                                  hidden={['RELATED']}
                                />
                              </div>
                            </FormItem>
                          )}
                        </div>
                      )
                    }
                    <FormItem
                      required
                      {...formItemLayout}
                      label={messages('request-2.key59')/*提交时占用预算*/}
                    >
                      <RadioGroup
                        disabled={disabled}
                        value={isBudgetEr}
                        onChange={e => this.handleStatusChange(e.target.value, 'isBudgetEr')}
                      >
                        <Radio value={true}>{messages('request-2.key332')/*占用*/}</Radio>
                        <Radio style={{marginLeft: 50}} value={false}>{messages('request-2.key333')/*不占用*/}</Radio>
                      </RadioGroup>
                    </FormItem>
                  </div>
                )
              }

              <Checkbox
                value={1002}
                key='1002'
                style={{marginTop: 12}}
                checked={availableType.indexOf(1002) > -1}
                onChange={e => this.handleStatusChange(e.target.value, 'availableType')}
              >
                {messages('request-2.key406')/*前期发票付款*/}
              </Checkbox>
              <div className='font-description'>{messages('request-2.key421')/*启用后，对公支付单界面显示新建前期发票按钮，用于录入前期已入账发票付款*/}</div>

              <Checkbox
                value={1003}
                key='1003'
                style={{marginTop: 12}}
                checked={availableType.indexOf(1003) > -1}
                onChange={e => this.handleStatusChange(e.target.value, 'availableType')}
              >
                {messages('request-2.key408')/*预付付款*/}
              </Checkbox>
              <div className='font-description'>{messages('request-2.key422')/*启用后，对公支付单界面显示新建预付付款按钮，用于录入无发票情况下的预付付款*/}</div>
              {
                availableType.indexOf(1003) > -1 && (
                  <FormItem
                    required
                    {...formItemLayout}
                    label={messages('request-2.key410')/*可见预付类型*/}
                  >
                    <CompactInput>
                      <Select
                        disabled={disabled}
                        style={{width: '100%'}}
                        onChange={value => this.handleChangeRange(value, 'prepaymentType')}
                        value={prepaymentType && prepaymentType.range}
                        getPopupContainer={triggerNode => triggerNode.parentNode}
                      >
                        <Option key={'ALL'}>{messages('common.all')/*全部*/}</Option>
                        <Option key={'PARTIAL'}>{messages('request-2.key10')/*部分*/}</Option>
                      </Select>
                      <Chooser
                        placeholder={messages('common.select')/*请选择*/}
                        labelKey='prepaymentTypeName'
                        valueKey='id'
                        selectorItem={{
                          ...chooserData['available_prepayment_type'],
                          url: `/api/prepayment/type/query/${setOfBooksId}`
                        }}
                        disabled={disabled || prepaymentTypeRangeDisabled}
                        onChange={value => this.handleStatusChange(value, 'prepaymentType')}
                        value={prepaymentType.value}
                        showNumber={true}
                      />
                    </CompactInput>
                  </FormItem>
                )
              }
            </FormItem>
            <FormItem
              required
              {...formItemLayout}
              label={messages('request-2.key411')/*默认付款方式*/}
            >
              <Select
                value={paymentMethod}
                disabled={disabled}
                placeholder={messages('common.select')/*请选择*/}
                defaultActiveFirstOption={false}
                showArrow={true}
                onChange={value => this.handleStatusChange(value, 'paymentMethod')}
                getPopupContainer={triggerNode => triggerNode.parentNode}>
                {paymentTypeList.map((option) => {
                  return <Option key={option.id}>{option.description}</Option>
                })}
              </Select>
            </FormItem>
            <FormItem
              required
              {...formItemLayout}
              label={messages('request-2.key44')/*关联申请单*/}
            >
              <RadioGroup
                disabled={disabled}
                value={applicationEnabled}
                onChange={e => this.handleStatusChange(e.target.value, 'applicationEnabled')}
              >
                <Radio value={true}>{messages('request-2.key32')/*关联*/}</Radio>
                <Radio style={{marginLeft: 50}} value={false}>{messages('request-2.key46')/*不关联*/}</Radio>
              </RadioGroup>
            </FormItem>
            {
              applicationEnabled && (
                <div>
                  <FormItem
                    required
                    {...formItemLayout}
                    label={<span><Icon type="enter" className="rotate-icon" />{messages('request-2.key412')/*可关联表单列表*/}</span>}
                  >
                    <CompactInput>
                      <Select
                        disabled={disabled}
                        style={{width: '100%'}}
                        onChange={value => this.handleChangeRange(value, 'requestFormType')}
                        value={requestFormType && requestFormType.range}
                        getPopupContainer={triggerNode => triggerNode.parentNode}
                      >
                        <Option key={'ALL'}>{messages('common.all')/*全部*/}</Option>
                        <Option key={'PARTIAL'}>{messages('request-2.key10')/*部分*/}</Option>
                      </Select>
                      <Chooser
                        placeholder={messages('common.select')/*请选择*/}
                        type='available_request_list'
                        labelKey='formName'
                        valueKey='formOID'
                        disabled={disabled || requestFormTypeRangeDisabled}
                        onChange={value => this.handleStatusChange(value, 'requestFormType')}
                        value={requestFormType.value}
                        listExtraParams={{
                          setOfBooksId: priorityValue.levelCode === 'SET_OF_BOOK' ? priorityValue.levelOrgId : null,
                          companyOID: priorityValue.levelCode === 'COMPANY' ? priorityValue.levelOrgId : null,
                        }}
                        showNumber={true}
                      />
                    </CompactInput>
                  </FormItem>
                  <FormItem
                    required
                    {...formItemLayout}
                    label={<span><Icon type="enter" className="rotate-icon" />{messages('request-2.key413')/*关联申请单范围*/}</span>}
                  >
                    <RadioGroup
                      disabled={disabled}
                      value={relatedApplicationScope}
                      onChange={e => this.handleStatusChange(e.target.value, 'relatedApplicationScope')}
                    >
                      <Radio value={1001}>{messages('request-2.key414')/*同申请人*/}</Radio>
                      <Radio value={1002}>{messages('request-2.key415')/*同部门*/}</Radio>
                      <Radio value={1003}>{messages('request-2.key416')/*同公司*/}</Radio>
                    </RadioGroup>
                  </FormItem>
                  <FormItem
                    required
                    {...formItemLayout}
                    label={messages('request-2.key417')/*关联申请单必填*/}
                  >
                    <RadioGroup
                      disabled={disabled}
                      value={relatedApplicationRequired}
                      onChange={e => this.handleStatusChange(e.target.value, 'relatedApplicationRequired')}
                    >
                      <Radio value={true}>{messages('request-2.key326')/*必填*/}</Radio>
                      <Radio style={{marginLeft: 50}} value={false}>{messages('request-2.key327')/*不必填*/}</Radio>
                    </RadioGroup>
                  </FormItem>
                </div>
              )
            }

            <div className="special-height">
              <FormItem
                required
                {...formItemLayout}
                label={messages('request-2.key37')/*关联合同*/}
              >
                <RadioGroup
                  disabled={disabled}
                  value={contractEnable}
                  onChange={e => this.handleStatusChange(e.target.value, 'contractEnable')}
                >
                  <Radio value={true}>{messages('request-2.key32')/*关联*/}</Radio>
                  <Radio style={{marginLeft: 50}} value={false}>{messages('request-2.key46')/*不关联*/}</Radio>
                </RadioGroup>
              </FormItem>

              {contractEnable && (
                <FormItem
                  required
                  {...formItemLayout}
                  label={<span><Icon type="enter" className="rotate-icon" />{messages('request-2.key325')/*关联合同必填*/}</span>}
                >
                  <RadioGroup
                    disabled={disabled}
                    value={contractRequired}
                    onChange={e => this.handleStatusChange(e.target.value, 'contractRequired')}
                  >
                    <Radio value={true}>{messages('request-2.key326')/*必填*/}</Radio>
                    <Radio style={{marginLeft: 50}} value={false}>{messages('request-2.key327')/*不必填*/}</Radio>
                  </RadioGroup>
                </FormItem>
              )}
            </div>

            <FormItem
              required
              {...formItemLayout}
              label={messages('request-2.key350')/*员工创建供应商*/}
            >
              <RadioGroup
                style={{width: '100%'}}
                disabled={disabled}
                value={addVenMaster}
                onChange={e => this.handleStatusChange(e.target.value, 'addVenMaster')}
              >
                <Radio style={{marginRight: 50}} value="false">{messages('request-2.key56')/*不可创建*/}</Radio>
                <Radio style={{marginRight: 50}} value="true">{messages('request-2.key351')/*可创建：供应商+银行账号*/}</Radio>
                <Radio value="bankOnly">{messages('request-2.key352')/*可创建：银行账号*/}</Radio>
              </RadioGroup>
            </FormItem>
          </Form>
        </Spin>
        <Affix offsetBottom={0} className="bottom-bar">
          {!disabled && (
            <Button type="primary" loading={loading} onClick={this.handleSave}>{messages('common.ok')/*确定*/}</Button>
          )}
          <Button style={{marginLeft: 15}} onClick={e => this.goBack(true)}>{messages('common.back')/*返回*/}</Button>
        </Affix>
      </div>
    )
  }
}

ExpenseReportProperty.propTypes = {
  refreshBase: React.PropTypes.func
};

function mapStateToProps(state) {
  return {
    currentMenuPermission: state.main.currentMenuPermission,
    profile: state.login.profile,
  }
}

ExpenseReportProperty.contextTypes = {
  formType: React.PropTypes.any,
  formOID: React.PropTypes.string,
  form: React.PropTypes.object,
  router: React.PropTypes.object,
  close: React.PropTypes.any
};

const WrappedExpenseReportProperty = Form.create()(ExpenseReportProperty);

export default connect(mapStateToProps)(WrappedExpenseReportProperty)
